<?php

declare(strict_types=1);

namespace App\Model;

use App\Model\Setting\SettingUserTags;
use Hyperf\DbConnection\Model\Model;

/**
 * 用户标签
 */
class UserTag extends Model
{
    protected $table = 'user_tag';
    protected $fillable = ['user_id', 'tag_id', 'flag', 'tag_type'];

    const TYPE_SELF = 1;
    const TYPE_LOVE = 2;

    static function updateTags($userId = 0, $tagIds = [], $tagType = self::TYPE_SELF)
    {
        if (empty($tagIds)) return false;
        //清空原标签
        self::clearTags($userId, $tagType);
        foreach ($tagIds as $tagId) {
            $where = [
                'user_id' => $userId,
                'tag_id' => $tagId,
                'tag_type' => $tagType,
            ];
            $info = array_merge($where, ['flag' => 1]);
            $ret = self::updateOrCreate($where, $info);
        }
        return $ret;
    }

    /**
     * 清空标签
     */
    static function clearTags($userId, $tagType = self::TYPE_SELF)
    {
        $where = [
            'user_id' => $userId,
            'tag_type' => $tagType,
            'flag' => 1
        ];
        return self::where($where)->update(['flag' => 0]);
    }

    static function getTagIds($userId = 0, $tagType = self::TYPE_SELF)
    {
        $where = [
            'user_id' => $userId,
            'tag_type' => $tagType,
            'flag' => 1,
        ];
        return self::where($where)->pluck('tag_id')->toArray();
    }

    static function getTagNames($userId = 0, $tagType = self::TYPE_SELF)
    {
        $tagIds = self::getTagIds($userId, $tagType);
        return SettingUserTags::where('flag', 1)->whereIn('id', $tagIds)->pluck('tag_name')->toArray();
    }
}
